package com.slaffka.dao;

import com.slaffka.ConnectionFactory;
import com.slaffka.mapper.UserMapper;
import com.slaffka.model._User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * _User: v.tsapaev
 * Date: 11.02.12
 * Time: 19:38
 * To change this template use File | Settings | File Templates.
 */
public class UserDAO {

    private SqlSessionFactory sqlSessionFactory;

    public UserDAO () {
        sqlSessionFactory = ConnectionFactory.getSqlSessionFactory();
    }
    
    public _User getUserById(Long id){
        _User user = null;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            user = userMapper.getUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return user;
    }
    
    public List<_User> getUsers(){
        List<_User> users = null;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            users = userMapper.getUsers();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return users;    
    }
    
    public void addUser(_User user){
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
        
}
